//
//  PersonalInfoVC.m
//  Collection
//
//  Created by Home on 9/15/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//



#define SCROLLVIEW_CONTENT_HEIGHT 460
#define SCROLLVIEW_CONTENT_WIDTH  320

#import "PersonalInfoVC.h"
#import "SignatureVC.h"
#import "VehicleController.h"


CGFloat animatedDistance;
static const CGFloat KEYBOARD_ANIMATION_DURATION = 0.3;
static const CGFloat MINIMUM_SCROLL_FRACTION = 0.2;
static const CGFloat MAXIMUM_SCROLL_FRACTION = 0.8;
static const CGFloat PORTRAIT_KEYBOARD_HEIGHT = 280;
static const CGFloat LANDSCAPE_KEYBOARD_HEIGHT = 162;
//anyView has been defined for different kind of views to avoid keyboard when entering data in textfield.
UIView *anyView;

@implementation PersonalInfoVC
@synthesize datePick;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)dealloc
{
    [drivableArr_ release];
    [dropDownView release];
	[datePick release];
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
	datePick.hidden = YES;
	[hideph setHidden:YES];


    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.navigationItem.title = @"Booking Details 1";
    
    UIBarButtonItem *settingNavigationItem = [[UIBarButtonItem alloc]initWithTitle:@"Next" style:UIBarButtonItemStyleBordered target:self action:@selector(buttonNextAction:)];
    settingNavigationItem.style = UIBarButtonItemStyleBordered;
    [self.navigationItem setRightBarButtonItem:settingNavigationItem];
    [settingNavigationItem release];
    
    cache = [NSUserDefaults standardUserDefaults];
    
    objSrollView_.contentSize = CGSizeMake(320, 660);
    
    drivableArr_ = [[NSArray alloc] initWithArray:[NSArray arrayWithObjects:@"Drivable1",@"Drivable2",@"Drivable3",nil]]; 
   // [driverNameBtn_ setTitle:[drivableArr_ objectAtIndex:0] forState:UIControlStateNormal];
    dropDownView = [[DropDownView alloc] initWithArrayData:drivableArr_ cellHeight:20 heightTableView:60 paddingTop:0 paddingLeft:-5 paddingRight:-10 refView:driverNameBtn_ animation:BLENDIN openAnimationDuration:2 closeAnimationDuration:2];
	//[driverNameBtn_ addTarget:self action:@selector(actionButtonClick) forControlEvents:UIControlEventTouchUpInside];
	dropDownView.delegate = self;
	[objSrollView_ addSubview:dropDownView.view];
	
	NSDate *selected=[NSDate date];
    NSDateFormatter *format = [[NSDateFormatter alloc]init];
    [format setDateFormat:@"dd/MM/YYYY"];
	
	dateTF_.text = [NSString stringWithFormat:@"%@",[format stringFromDate:selected]];
	
	[format setTimeStyle:kCFDateFormatterShortStyle];
	timeTF_.text = [format stringFromDate:selected];
	timeOutTF_.text = [NSString stringWithFormat:@"%@",[format stringFromDate:selected]];
	timeBackTF_.text = [NSString stringWithFormat:@"%@",[format stringFromDate:selected]];

	[format release];
	
	if (arrData.count>0) {
	
	
		//NSLog(@"fieldsVal%@",fieldsVal);
		//NSLog(@"Contact~~~%@",[NSNull null]);
		
		fieldsVal = [arrData objectAtIndex:0];
	
    
	if ([fieldsVal valueForKey:@"ContactName"]!=[NSNull null]) { 
		
		contactNameTF_.text = [fieldsVal valueForKey:@"ContactName"];
	}
	
	if ([fieldsVal objectForKey:@"AddressLine1"] != [NSNull null]) { 
		
		address1TF_.text = [fieldsVal valueForKey:@"AddressLine1"];
	}
	
	if ([fieldsVal objectForKey:@"AddressLine2"] != [NSNull null]) { 
		
		address2TF_.text = [fieldsVal valueForKey:@"AddressLine2"];
	}
	
	if ([fieldsVal objectForKey:@"County"] != [NSNull null]) { 
		
		countryTF_.text = [fieldsVal valueForKey:@"County"];
	}
	
	if ([fieldsVal objectForKey:@"MobilePhone1"] != [NSNull null]) { 
		
		phoneTF_.text = [fieldsVal valueForKey:@"MobilePhone1"];
	}
	
	if ([fieldsVal objectForKey:@"MobilePhone1"] != [NSNull null]) { 
		
		phoneTF_.text = [fieldsVal valueForKey:@"MobilePhone1"];
	}
	
	if ([fieldsVal objectForKey:@"PostCode"] != [NSNull null]) { 
		
		postCodeTF_.text = [fieldsVal valueForKey:@"PostCode"];
	}
	
	if ([fieldsVal objectForKey:@"Town"] != [NSNull null]) { 
		
		townTF_.text = [fieldsVal valueForKey:@"Town"];
	}
	
	
	}
	else {
		
		UIAlertView *alert =[[UIAlertView alloc] initWithTitle:@"Alert" message:@"No Booking ID Found." delegate:self cancelButtonTitle:@"Stay here" otherButtonTitles:@"Back", nil];
		[alert show];
		[alert release];
		
	}

		
	
}

-(void)datepickerAction
{
	
	datePick.hidden = NO;
	[hideph setHidden:NO];
	[datePick setDatePickerMode:UIDatePickerModeDate];
	 datePick.frame = CGRectMake(0,208,322,216);

	[phoneTF_ resignFirstResponder];
     
	/*UIActionSheet *alert = [[UIActionSheet alloc]initWithTitle:@"Select" delegate:nil cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:nil];
	datePick.hidden = NO;
	CGRect frame = CGRectMake(0,40,0,0);
	[datePick setFrame:frame];
	//datePick.superview = YES;
	[alert addSubview:datePick];
	
    [alert setBounds:CGRectMake(0, 200, 320, 0)];
	[alert showInView:objSrollView_];
	//[alert becomeFirstResponder];
	
	//[message release];
	[alert release];*/
	
	/*UIActionSheet *aac = [[UIActionSheet alloc] initWithTitle:@"How many?"
													 delegate:self
											cancelButtonTitle:nil
									   destructiveButtonTitle:nil
											otherButtonTitles:nil];
	
	UIDatePicker *theDatePicker = [[UIDatePicker alloc] initWithFrame:CGRectMake(0.0, 44.0, 0.0, 0.0)];
	
	
	datePick = theDatePicker;
	[theDatePicker release];
	[datePick addTarget:self action:@selector(dateChanged) forControlEvents:UIControlEventValueChanged];
	
	UIToolbar *pickerDateToolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
	pickerDateToolbar.barStyle = UIBarStyleBlackOpaque;
	[pickerDateToolbar sizeToFit];
	
	NSMutableArray *barItems = [[NSMutableArray alloc] init];
	
	UIBarButtonItem *flexSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
	[barItems addObject:flexSpace];
	
	UIBarButtonItem *doneBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:nil];
	[barItems addObject:doneBtn];
	
	[pickerDateToolbar setItems:barItems animated:YES];
	
	[aac addSubview:pickerDateToolbar];
	[pickerDateToolbar release];
	datePick.hidden  = YES;
	UIView *dtView = [[UIView alloc]initWithFrame:datePick.frame];
	[aac addSubview:dtView];
	[dtView release];
	//[datePick release];
	//aac.frame =  CGRectMake(0, 200 , 320, 464);
	[aac setBounds:CGRectMake(0,200 ,320, 464)];

	[aac showInView:self.view];*/
	
}

-(id)initWithWebData:(NSArray*)arr
{
	arrData = [arr copy];
	return self;
}

-(void)dateChanged{


}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


-(IBAction)buttonNextAction:(id)sender;{
    
    [cache setValue:contactNameTF_.text forKey:@"contactName"];
    [cache setValue:dateTF_.text forKey:@"date"];
    [cache setValue:phoneTF_.text forKey:@"phone"];
    [cache setValue:timeTF_.text forKey:@"time"];
    [cache setValue:address1TF_.text forKey:@"address1"];
    [cache setValue:address2TF_.text forKey:@"address2"];
    [cache setValue:townTF_.text forKey:@"town"];
    [cache setValue:countryTF_.text forKey:@"country"];
    [cache setValue:jobTF_.text forKey:@"jobNo"];
    [cache setValue:timeOutTF_.text forKey:@"timeOut"];
    [cache setValue:timeBackTF_.text forKey:@"timeBack"];
    [cache setValue:mileageTF_.text forKey:@"mileage"];
    [cache setValue:postCodeTF_.text forKey:@"postCode"];
    [cache setValue:driverNameBtn_.text forKey:@"driverName"];
	[cache setValue:[fieldsVal valueForKey:@"ManufacturerID"] forKey:@"ManufacturerID"];
	[cache setValue:[fieldsVal valueForKey:@"Model"] forKey:@"Model"];
	[cache setValue:[fieldsVal valueForKey:@"PaintCodeColour"] forKey:@"color"];
	[cache setValue:[fieldsVal valueForKey:@"RegNumber"] forKey:@"reg"];


    VehicleController *objVehicleController = [[VehicleController alloc] init];
    [self.navigationController pushViewController:objVehicleController animated:YES];
    [objVehicleController release];
}



- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    if ([text isEqualToString:@"\n"]) {
        
        [textView resignFirstResponder];
        return NO;
    }
    return YES;
}
	
#pragma mark AlertView delegate.
	
	
	- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
	{
		if (buttonIndex ==1)
		{
			[self.navigationController popViewControllerAnimated:YES];
			
		}
	}

#pragma mark -
#pragma mark DropDownViewDelegate

-(void)dropDownCellSelected:(NSInteger)returnIndex{
        [driverNameBtn_ setTitle:[drivableArr_ objectAtIndex:returnIndex] forState:UIControlStateNormal];
        driverNameBtn_.tag = returnIndex;
       
        
}


-(void)actionButtonClick{

	[dropDownView openAnimation];
	//[driverNameBtn_ addSubview:dropDownView.view];

}
#pragma mark -
#pragma mark TextView Delegate

-(BOOL) textFieldShouldBeginEditing:(UITextField*)textField {
	activeField = textField;
	if (textField == dateTF_||textField==timeBackTF_||textField==timeOutTF_||textField==timeTF_)
	{
		[phoneTF_ resignFirstResponder];
		[contactNameTF_ resignFirstResponder];
		[jobTF_ resignFirstResponder];
		[mileageTF_ resignFirstResponder];
		[phoneTF_ resignFirstResponder];
		[hideph setHidden:YES];

	}
	
	
	return YES;
	
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
	[textField resignFirstResponder];
	return YES;
}


- (void)textFieldDidBeginEditing:(UITextField *)textField
{
	
	
		
	textField.returnKeyType = UIReturnKeyDone;
	textField.keyboardAppearance = UIKeyboardAppearanceAlert;
	
		anyView=objSrollView_;
	
	
 	CGRect textFieldRect = [anyView.window convertRect:textField.bounds fromView:textField];
 	CGRect viewRect =
 	[anyView.window convertRect:self.view.bounds fromView:objSrollView_];
 	CGFloat midline = textFieldRect.origin.y + 0.5 * textFieldRect.size.height;
 	CGFloat numerator =
 	midline - viewRect.origin.y
 	- MINIMUM_SCROLL_FRACTION * viewRect.size.height;
 	CGFloat denominator =
 	(MAXIMUM_SCROLL_FRACTION - MINIMUM_SCROLL_FRACTION)
 	* viewRect.size.height;
 	CGFloat heightFraction = numerator / denominator;
 	if (heightFraction < 0.0)
 	{ 
		heightFraction = 0.0;
 	}
 	else if (heightFraction > 1.0)
 	{
		heightFraction = 1.0;
 	}
 	UIInterfaceOrientation orientation =
 	
	[[UIApplication sharedApplication] statusBarOrientation];
 	if (orientation == UIInterfaceOrientationPortrait ||
		orientation == UIInterfaceOrientationPortraitUpsideDown)
 	{
		animatedDistance = floor(PORTRAIT_KEYBOARD_HEIGHT * heightFraction);
 	}
 	else
 	{
		animatedDistance = floor(LANDSCAPE_KEYBOARD_HEIGHT * heightFraction);
 	}
	
 	CGRect viewFrame = objSrollView_.frame;
 	viewFrame.origin.y -= animatedDistance;
	
 	[UIView beginAnimations:nil context:NULL];
 	[UIView setAnimationBeginsFromCurrentState:YES];
 	[UIView setAnimationDuration:KEYBOARD_ANIMATION_DURATION];
 	[anyView setFrame:viewFrame];
 	[UIView commitAnimations];	
	
	    
	    [hideph setHidden:YES];
	     datePick.hidden =YES;

	    //for date textfield
        
	if (textField.tag ==100) {
        [contactNameTF_ resignFirstResponder];
		[textField resignFirstResponder];
		[self performSelector:@selector(datepickerAction) withObject:nil afterDelay:0.002];
		hideph.frame = CGRectMake(0.00, 165.00, 322.0, 44.0);
			timeInteger =100;
		
		/*UIViewController *pickerView = [[UIViewController alloc]init];
		 
		 pickerView.view.frame = CGRectMake(0, 100, 320, 150);
		 hideph.frame = CGRectMake(0.00, 177.00, 322.0, 44.0);
		 
		 [pickerView.view addSubview:datePick];
		 [pickerView.view addSubview:hideph];
		 
		 [datePick setHidden:NO];
		 [hideph setHidden:NO];
		 [self presentModalViewController:pickerView animated:YES];
		 self.modalViewController.view.frame = pickerView.view.frame;
		 */
	}
	
	//for phone textfield
	if (textField.tag ==101) {
		
		[dateTF_ resignFirstResponder];
		 datePick.hidden =YES;
		
		[hideph setHidden:NO];
		
		hideph.frame = CGRectMake(0.00, 160.00, 322.0, 44.0);
		
	}
	
	
	if (textField.tag ==102) {
		[textField resignFirstResponder];
		[hideph setHidden:NO];
		hideph.frame = CGRectMake(0.00, 168.00, 322.0, 44.0);
        timeInteger =102;
		[datePick setDatePickerMode:UIDatePickerModeTime];
		datePick.frame = CGRectMake(0,208,322,216);

		[datePick setHidden:NO];
		}
	
	
	
	
		
	if (textField.tag ==103) {
		[textField resignFirstResponder];

		[hideph setHidden:NO];
		hideph.frame = CGRectMake(0.00, 162.00, 322.0, 44.0);
        timeInteger =103;
		[datePick setDatePickerMode:UIDatePickerModeTime];
		NSLog(@"picker Y %d",datePick.frame.size.height);
		datePick.frame = CGRectMake(0,200, 322,216);
		NSLog(@"picker Y %d",datePick.frame.size.height);

		[datePick setHidden:NO];
	}
	if (textField.tag ==104) {
		[textField resignFirstResponder];

		[hideph setHidden:NO];
		hideph.frame = CGRectMake(0.00, 162.00, 322.0, 44.0);
        timeInteger =104;
		[datePick setDatePickerMode:UIDatePickerModeTime];
		datePick.frame = CGRectMake(0,200,322,216);

		[datePick setHidden:NO];
	}
	if (textField.tag ==105) {
		[hideph setHidden:NO];
		
		hideph.frame = CGRectMake(0.00, 440.00, 322.0, 44.0);
	}
	if (textField == mileageTF_) {
		[hideph setHidden:NO];
		textField.keyboardType = UIKeyboardTypeNumberPad;
		hideph.frame = CGRectMake(0.00, 160.00, 322.0, 44.0);
	}

	
}


-(IBAction)hidekeypad
{
	 
	 hideph.hidden = YES;
	 datePick.hidden = YES; 
	[phoneTF_ resignFirstResponder];
	[mileageTF_ resignFirstResponder];
	if (timeInteger==100)
	{
	NSDate *selected=[datePick date];
    NSDateFormatter *format = [[NSDateFormatter alloc]init];
    [format setDateFormat:@"dd/MM/YYYY"];
	
	dateTF_.text = [NSString stringWithFormat:@"%@",[format stringFromDate:selected]];
	[format release];
	}
	
	if (timeInteger==102)
	{
		NSDate *selected=[datePick date];
		NSDateFormatter *format = [[NSDateFormatter alloc]init];
		
		[format setTimeStyle:kCFDateFormatterShortStyle];
		timeTF_.text = [NSString stringWithFormat:@"%@",[format stringFromDate:selected]];
		[format release];
	}
	
	if (timeInteger==103)
	{
		NSDate *selected=[datePick date];
		NSDateFormatter *format = [[NSDateFormatter alloc]init];
		
		[format setTimeStyle:kCFDateFormatterShortStyle];
		timeOutTF_.text = [NSString stringWithFormat:@"%@",[format stringFromDate:selected]];
		[format release];
	}
	
	if (timeInteger==104)
	{
		NSDate *selected=[datePick date];
		NSDateFormatter *format = [[NSDateFormatter alloc]init];
		
		[format setTimeStyle:kCFDateFormatterShortStyle];
		timeBackTF_.text = [NSString stringWithFormat:@"%@",[format stringFromDate:selected]];
		[format release];
	}
	
	timeInteger = 1000;
	
	
}



- (void)textFieldDidEndEditing:(UITextField *)textField
{
	if (textField==mileageTF_) {
		
	}
	CGRect viewFrame = objSrollView_.frame;
	viewFrame.origin.y += animatedDistance;
	[UIView beginAnimations:nil context:NULL];
	[UIView setAnimationBeginsFromCurrentState:YES];
	[UIView setAnimationDuration:KEYBOARD_ANIMATION_DURATION];
	[anyView setFrame:viewFrame];
	[UIView commitAnimations];
}


@end
